<template>
  <el-dialog :title="`${row?.id ? '编辑' : '新增'}用户`" :model-value="modelValue" width="700px" @close="commEvent.onClose">
    <el-form ref="formRef" :model="formValue" :rules="rules" :disabled="isAdmin">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="account" label="用户账号">
            <el-input placeholder="用户账号" v-model="formValue.account"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="status" label="账号状态">
            <el-radio-group v-model="formValue.status">
              <el-radio v-for="item in statusOptions" :key="item.value" :value="item.value" :label="item.label" />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="name" label="用户名称">
            <el-input placeholder="用户名称" v-model="formValue.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="sex" label="用户性别：">
            <el-radio-group v-model="formValue.sex">
              <el-radio :value="item.value" v-for="(item, index) in genderOptions" :key="index">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="phone" label="手机号码">
            <el-input placeholder="手机号码" maxlength="11" v-model="formValue.phone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="email" label="电子邮箱">
            <el-input placeholder="电子邮箱" v-model="formValue.email"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="roleIds" label="用户角色">
            <el-select v-model="formValue.roleIds" multiple placeholder="用户角色" filterable>
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="item.roleKey === 'system-admin'"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="deptIds" label="所属部门">
            <el-tree-select
              v-model="formValue.deptIds"
              :data="depts"
              multiple
              default-expand-all
              check-strictly
              show-checkbox
              :render-after-expand="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="commEvent.onClose">取消</el-button>
      <el-button type="primary" @click="commEvent.onSubmit" :disabled="isAdmin">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, PropType, watch, nextTick } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { statusOptions, genderOptions } from "@/utils/dict"
import { getUserDetailApi, getRoleAllApi, getDeptTreeApi, saveUserApi } from "@/api/modules/system"
import { SystemSpace } from "@/api/interface/system"
interface Options {
  label: string
  value: number
  disabled?: boolean
  children?: Options[]
}
const props = defineProps({
  modelValue: Boolean,
  row: { type: Object as PropType<SystemSpace.UserPageList>, default: () => {} }
})
const emit = defineEmits(["update:modelValue", "refresh"])
// 参数
const formRef = ref<FormInstance>() // 表单实例
const roles = ref<SystemSpace.RoleCate[]>([]) // 角色列表
const depts = ref<Options[]>([]) // 部门数据
const isAdmin = ref<boolean>(false) // 是否是管理员
// 表单数据
const formValue = ref({
  account: "", // 用户账号
  status: 0 as 0 | 1, // 账号状态
  name: "", // 用户名称
  sex: 0 as 0 | 1 | 2,
  phone: "", // 手机号码
  email: "", // 电子邮箱
  roleIds: [] as number[], // 用户角色
  deptIds: [] as number[] // 部门
})
// 表单校验规则
const rules: FormRules = {
  account: [{ required: true, message: "请输入用户账号", trigger: "blur" }],
  name: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  email: [{ pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/, message: "请输入正确的电子邮箱", trigger: "blur" }],
  roleIds: [{ required: true, message: "请选择用户角色", trigger: "change" }]
}
// 事件
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },
  // 获取详情
  getDetail: async (id: number) => {
    const { data } = await getUserDetailApi({ id })
    const { account, status, name, sex, phone, email, roleList, deptList } = data
    const roleIds = roleList.map(item => item.id)
    const deptIds = deptList.map(item => item.id)
    formValue.value = { account, status, name, sex, phone, email, roleIds, deptIds }
    const roleKey: string = roles.value.find(item => item.id === id)?.roleKey || ""
    isAdmin.value = roleKey === "system-admin"
  },
  // 获取角色信息
  getRoles: async () => {
    const { data } = await getRoleAllApi()
    roles.value = data
  },
  // 获取部门信息
  getDepts: async () => {
    const { data } = await getDeptTreeApi({})
    depts.value = commEvent.formatDept(data)
  },
  //格式化部门树
  formatDept: (data?: SystemSpace.DeptTree[]): Options[] => {
    if (!data || data.length <= 0) return []
    return data.map(item => ({
      label: item.name,
      value: item.id,
      disabled: item.status === 1,
      children: commEvent.formatDept(item.children)
    }))
  },
  // 表单提交
  onSubmit: () => {
    if (!formRef.value) return
    formRef.value.validate(async valid => {
      if (!valid) return
      const params: SystemSpace.UserAdd = { ...formValue.value }
      if (props.row?.id) {
        params.id = props.row.id
      }
      const { code } = await saveUserApi(params)
      if (code !== "200") return
      ElMessage.success("操作成功")
      commEvent.onClose()
      emit("refresh")
    })
  }
}
watch(
  () => props.modelValue,
  flag => {
    if (flag) {
      nextTick(() => {
        formRef.value?.resetFields()
        isAdmin.value = false
        commEvent.getRoles()
        commEvent.getDepts()
        if (props.row?.id) {
          commEvent.getDetail(props.row.id)
        }
      })
    }
  }
)
</script>

<style scoped></style>
